package ru.ifmo.tanya.handler;

import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import ru.ifmo.tanya.util.StreamUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Set;


public class StaticHandler extends AbstractHandler {

    private static final Logger LOG = Logger.getLogger(StaticHandler.class);

    private static final Charset UTF_8 = Charset.forName("UTF-8");

    private final Set<String> availableExtensions = new HashSet<>();
    {
        availableExtensions.add("html");
        availableExtensions.add("js");
        availableExtensions.add("css");
        availableExtensions.add("jpg");
        availableExtensions.add("ico");
    }

    private static final String indexFileName = "html/index.html";

    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if ("/".equals(target)) {
            target = "/" + indexFileName;
        }

        final String extension = target.substring(target.lastIndexOf('.') + 1);
        if (!availableExtensions.contains(extension)) {
            LOG.warn("Extension " + extension + " is not available!");
            return;
        }

        InputStream resource = getClass().getResourceAsStream(target);
        if (resource != null) {
            response.setStatus(HttpServletResponse.SC_OK);
            response.setCharacterEncoding(UTF_8.name());
        } else {
            System.out.println(target + " not found!");
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        final ServletOutputStream output = response.getOutputStream();
        StreamUtil.transferData(resource, output);
        output.close();
    }
}
